<?php
/*
 * @Descripttion: 
 * @Author: dedeye
 * @Date: 2020-02-25 23:51:57
 * @LastEditors: dedeye
 * @LastEditTime: 2020-03-01 15:49:48
 */

namespace app\admin\controller;

use app\admin\model\Admin as AdminModel;
use app\admin\validate\AdminValidate;
use app\common\util\ReturnCode;

class Admin extends Controller
{
    /**
     * 显示资源列表
     *
     * @return \think\Response
     */
    public function index()
    {
        if(!request()->isAjax())
            return $this->fetch();
        $data = input('get.');
        $checkData = self::checkData(new AdminValidate, 'select', $data);
        if(!is_null($checkData)) {
            return resultJson(ReturnCode::PARAM_ERROR, $checkData);
        }
        $where = [];
        if(isset($data['username'])) {
            $where[] = ['username', 'like', '%'.$data['username'].'%'];
        }
        if(isset($data['nickname'])) {
            $where[] = ['nickname', 'like', '%'.$data['nickname'].'%'];
        }
        $field = 'id, nickname, username, status, create_ip, create_time';
        $limit = 10;
        if(isset($data['limit']) && is_numeric($data['limit'])) {
            $limit = $data['limit'];
        }
        $admins = AdminModel::field($field)->where($where)->append(['status_text'])->paginate($limit);
        if($admins->isEmpty()) {
            return resultJson(ReturnCode::RESULT_NULL, '暂无数据');
        }
        return resultJson(ReturnCode::SUCCESS, 'success', $admins);
    }

    /**
     * 创建资源表单页.
     *
     * @return \think\Response
     */
    public function create()
    {
        if(!request()->isPost() || !request()->isAjax()){
            return $this->fetch('add');
        }
        $data = input('post.');
        $checkData = self::checkData(new AdminValidate, 'add', $data);
        if(!is_null($checkData)) {
            return resultJson(ReturnCode::PARAM_ERROR, $checkData);
        }
        $admin = new AdminModel;
        $data['create_ip'] = request()->ip();
        $data['salt'] = rand(100000, 999999);
        $data['password'] = md5($data['password'].$data['salt']);
        $addRes = $admin->allowField(true)->save($data);
        if(!$addRes) {
            return resultJson(ReturnCode::RESULT_FAIL, '添加失败');
        }
        return resultJson(ReturnCode::SUCCESS, '添加成功');
    }

    /**
     * 显示指定的资源
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function read($id)
    {
        $field = 'id, nickname, username, status';
        $admin = AdminModel::field($field)->get($id);
        if(is_null($admin)) {
            return resultJson(ReturnCode::RESULT_NULL, '用户不存在');
        }
        return resultJson(ReturnCode::SUCCESS, 'success', $admin);
    }

    /**
     * 修改资源.
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function edit()
    {
        if(!request()->isPost() || !request()->isAjax()){
            return $this->fetch('edit');
        }
        $data = input('post.');
        $checkData = self::checkData(new AdminValidate, 'edit', $data);
        if(!is_null($checkData)) {
            return resultJson(ReturnCode::PARAM_ERROR, $checkData);
        }
        $id = $data['id'];
        unset($data['id']);
        $admin = new AdminModel;
        $hasAdmin = $admin->get($id);
        if(is_null($hasAdmin)) {
            return resultJson(ReturnCode::RESULT_NULL, 'id无效');
        }
        if($data['username'] !== $hasAdmin->username) {
            $adminOnly = $admin->where('id<>:id and username=:username')
                        ->bind(['id' => [$id, \PDO::PARAM_INT] , 'username' => $data['username']])
                        ->find();
            if(!is_null($adminOnly)) {
                return resultJson(ReturnCode::RESULT_NULL, '账号存在');
            }
        }
        $updateRes = $admin->allowField(true)->save($data, ['id' => $id]);
        if(!$updateRes) {
            return resultJson(ReturnCode::RESULT_FAIL, '修改失败');
        }
        return resultJson(ReturnCode::SUCCESS, '修改成功');
    }

    /**
     * 删除指定资源
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function delete($id)
    {
        if(config('admin.super_admin') == $id) {
            return resultJson(ReturnCode::FAIL, '超级管理员无法删除');
        }
        if(session('admin_id') == $id) {
            return resultJson(ReturnCode::FAIL, '您无法删除自己的账号');
        }
        $admin = AdminModel::get($id);
        if(is_null($admin)) {
            return resultJson(ReturnCode::RESULT_NULL, '账号不存在');
        }
        $delRes = $admin->delete();
        if(!$delRes) {
            return resultJson(ReturnCode::RESULT_FAIL, '删除失败');
        }
        return resultJson(ReturnCode::SUCCESS, '删除成功');
    }

     /**
     * 删除指定多个资源
     *
     * @param  int  $id
     * @return \think\Response
     */
    // public function deletes()
    // {
    //     $data = input('post.');
    //     if(!isset($data['ids'])) {
    //         return resultJson(ReturnCode::PARAM_ERROR, '未选择删除用户');
    //     }
    //     $delsRes = AdminModel::destroy($data['ids']);
    //     if(!$delsRes) {
    //         return resultJson(ReturnCode::RESULT_FAIL, '删除失败');
    //     }
    //     return resultJson(ReturnCode::SUCCESS, '删除成功');
    // }

    public function auth()
    {
        return $this->fetch('auth');
    }

    public function authlist($id)
    {
        $admin = AdminModel::with('groups')->get($id)->hidden(['groups.pivot']);
        if(is_null($admin)) {
            return resultJson(ReturnCode::RESULT_NULL, '用户id错误');
        }
        return resultJson(ReturnCode::SUCCESS, 'success', $admin->toArray());
    }

    public function authAdd($id, $groupid)
    {
        if($id == config('admin.super_admin')) {
            return resultJson(ReturnCode::FAIL, '超级管理员，拥有所有权限');
        }
        $admin = AdminModel::get($id, 'groups');
        if(is_null($admin)) {
            return resultJson(ReturnCode::RESULT_NULL, '用户id错误');
        }
        $groups = $admin->groups;
        foreach($groups as $k => $v) {
            if($v['id'] == $groupid) {
                return resultJson(ReturnCode::PARAM_INVALID, '该规则组已添加');
            }
        }
        $group = \app\admin\model\RuleGroup::get($groupid);
        if(is_null($group)) {
            return resultJson(ReturnCode::RESULT_NULL, '规则组id错误');
        }
        $authRes = $admin->groups()->save($groupid);
        if(!$authRes) {
            return resultJson(ReturnCode::RESULT_FAIL, '添加规则组失败');
        }
        return resultJson(ReturnCode::SUCCESS, '添加用户组成功');
    }

    public function authDel($id, $groupid)
    {
        if($id == config('admin.super_admin')) {
            return resultJson(ReturnCode::FAIL, '超级管理员账号无法删除');
        }
        $admin = AdminModel::get($id, 'groups');
        if(is_null($admin)) {
            return resultJson(ReturnCode::RESULT_NULL, '用户id错误');
        }
        $delRes = $admin->groups()->detach($groupid);
        if(!$delRes) {
            return resultJson(ReturnCode::RESULT_FAIL, '删除规则组失败');
        }
        return resultJson(ReturnCode::SUCCESS, '删除用户组成功');
    }
}
